var util = require('util');

var constants = require('./constants.js');
var oauth = require('oauth');

var oa = null;

var initialize = exports.initialize =  function(request_token_url, access_token_url) {
	oa= new oauth.OAuth(request_token_url, access_token_url,
            constants.oauth.CONSUMER_KEY, constants.oauth.CONSUMER_SECRET,
            "1.0", null, "HMAC-SHA1");
};

var getRequestToken = exports.getRequestToken = function(handler) {
	if (!oa) {
		throw 'oauth module not initialized.';
	}
	
	oa.getOAuthRequestToken(function(error, oauth_token, oauth_token_secret, results){
		if(error) console.log('error :' + error);
		else { 
			console.log('oauth_token: ' + oauth_token);
			console.log('oauth_token_secret: ' + oauth_token_secret);
			console.log('request token results: ' + util.inspect(results));
			
			handler(oauth_token, oauth_token_secret);
		}
	});	
};

var getAccessToken = exports.getAccessToken = function(oauth_token, oauth_token_secret, handler) {
	if (!oa) {
		throw 'oauth module not initialized.';
	}
	
	oa.getOAuthAccessToken(oauth_token, oauth_token_secret, function(error, oauth_access_token, oauth_access_token_secret, results) {
		if (error) {
			console.log(JSON.stringify(error));
		}
		
		console.log('oauth_access_token: ' + oauth_access_token);
		console.log('oauth_access_token_secret: ' + oauth_access_token_secret);
		console.log('access token results: ' + util.inspect(results));
		
		handler(oauth_access_token, oauth_access_token_secret);
	});
};

var post = exports.post = function(url, data, type, oauth_access_token, oauth_access_token_secret) {
	if (!oa) {
		throw 'oauth module not initialized.';
	}
	
	oa.post(url, oauth_access_token, oauth_access_token_secret, data, type, function(error, result) {
		console.log('error: ' + JSON.stringify(error));
		console.log('data: ' + result);
	});
};